package ru.p03.tvipuskeditor.client.tvipuskeditor;

import org.vaadin.addons.maskedtextfield.client.MaskedTextFieldWidget;

import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.NativeEvent;
import com.google.gwt.dom.client.Node;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.Event.NativePreviewEvent;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Hyperlink;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.TextBoxBase;
import com.google.gwt.user.client.ui.VerticalPanel;

public class TagAttrsDialog extends DialogBox {

  	protected final MaskedTextFieldWidget tfTimeS;

	private final MaskedTextFieldWidget tfTimePo;
	
	private String lastValuePo = ""; 

	private final Label lFilename;
	
	final Hyperlink hfilenameLink;

	final Label lDuration;
	
	private final TextArea tfTitleBlock;
	
	private final Button btnAttachFile;
	
	private Node closeEventTarget = null;
	
	boolean isCanceled = false;

	private TvipuskEditorWidget vTvipuskEditorInstance = null;
	
	protected String fullFileName = "";

	private String block_type  = "";

	public TagAttrsDialog(TvipuskEditorWidget vTvipuskEditor) {
		super();
// 		Set the dialog box's caption.
//		center();
//	   setModal(true);
	   this.vTvipuskEditorInstance  = vTvipuskEditor;
	   //get the "dialogTopRight" class td ssdsd
	   Element dialogTopRight = getCellElement(0, 2);		
	   dialogTopRight.setInnerHTML(
	            "<div style=\"margin-left:-25px;margin-top: 7px;\">" + 
	            "<img src=\"images/closebutton.png\" height=\"20px\"/>" + 
	            "</div>");

	    // set the event target
	    closeEventTarget = dialogTopRight.getChild(0).getChild(0);		

		tfTimeS = new MaskedTextFieldWidget();
	    //tfTimeS = new TextBox();
		tfTimeS.setColumns(8);
		tfTimeS.setMask("##:##:##");

		tfTimePo = new MaskedTextFieldWidget();
	    //tfTimePo = new TextBox();
		tfTimePo.setColumns(8);
		tfTimePo.setMask("##:##:##");

		tfTimePo.addChangeHandler(new ChangeHandler() {

			@Override
			public void onChange(ChangeEvent event) {
				GWT.log("tfTimePo.onChange");
				if (!"".equals(tfTimePo.getText())){
					lastValuePo = tfTimePo.getText();	
				}else{
					tfTimePo.setText(lastValuePo);
				}
			}
		});

		lFilename = new Label();
		lFilename.setText("Файл: ");

		hfilenameLink = new Hyperlink();
		hfilenameLink.setWidth("100px");
		//hfilenameLink.setText("ссылка на имя файла");
		hfilenameLink.setText("");
		hfilenameLink.addClickHandler(new ClickHandler() {
			
			@Override
			public void onClick(ClickEvent event) {
				vTvipuskEditorInstance.onFileLinkClick();
			}
		});
				
		lDuration = new Label();
		lDuration.setText("Длительность: ");
		
		tfTitleBlock = new TextArea();
		tfTitleBlock.setTitle("Титры:");
		tfTitleBlock.setWidth("180px");
		tfTitleBlock.setHeight("50px");
		
		//tfFileName = new TextBox();
		btnAttachFile = new Button("Прикрепить файл");
		
		btnAttachFile.addClickHandler(new ClickHandler() {
		 
			@Override
			public void onClick(ClickEvent event){
				vTvipuskEditorInstance.chooseFile();
			}
		});

	    // DialogBox is a SimplePanel, so you have to set its widget property to
	    // whatever you want its contents to be.
	    Button ok = new Button("OK");
	    ok.addClickHandler(new ClickHandler() { 

			@Override
			public void onClick(ClickEvent event) {
				// TODO Auto-generated method stub
				//Проверка что По больше чем С
				String s = tfTimeS.getText();
				String po = tfTimePo.getText();
				if (s.compareTo(po) >= 0){
					//lError.setText("Время По больше времени С");
					Window.alert("Время С больше времени По. Введите другое время.");
				}else{
					TagAttrsDialog.this.hide();
				}
			}
		});
	    
		final VerticalPanel timeAttrPanel = new VerticalPanel();

		timeAttrPanel.setSpacing(5);
		
		timeAttrPanel.add(createTextBox(tfTimeS,"&#160;C:&#160;"));		

		timeAttrPanel.add(createTextBox(tfTimePo,"По:"));

		timeAttrPanel.add(lFilename);

		timeAttrPanel.add(hfilenameLink);
		
		timeAttrPanel.add(lDuration);
		
		//timeAttrPanel.add(createTextBox(tfTitleBlock,"Заголовок блока:"));
		
		timeAttrPanel.add(new HTML("Титры:"));
		timeAttrPanel.add(tfTitleBlock);

		timeAttrPanel.add(btnAttachFile);

		timeAttrPanel.add(ok);

		//setWidget(ok);
	    setWidget(timeAttrPanel);
	}

	@Override
	protected void onPreviewNativeEvent(NativePreviewEvent event) {
	    NativeEvent nativeEvent = event.getNativeEvent();

	    if (!event.isCanceled() 
	    		&& (event.getTypeInt() == Event.ONCLICK)  
   				&& isCloseEvent(nativeEvent))
	    
//	    if (!event.isCanceled()
//	        && ( (event.getTypeInt() == Event.ONCLICK) || 
//	        		( (event.getTypeInt() == Event.ONKEYDOWN) && 
//	        		  (event.getNativeEvent().getKeyCode() == KeyCodes.KEY_ESCAPE))
//	            ) 
//	        && isCloseEvent(nativeEvent))
	    {
	    	isCanceled = true;
	        this.hide();
	        isCanceled = false;
	    }
	    super.onPreviewNativeEvent(event);
	}

	// see if the click target is the close button
	private boolean isCloseEvent(NativeEvent event) {
	    return event.getEventTarget().equals(closeEventTarget); //compares equality of the underlying DOM elements
	}   
	
	
	
	
	private HorizontalPanel createTextBox(final TextBoxBase textBox, String caption){
	    HorizontalPanel hPanel = new HorizontalPanel();
	    hPanel.setSpacing(4);
	    hPanel.add(new HTML(caption));
	    hPanel.add(textBox);
	    return hPanel;
	}

	
	/**
	 * Формирует строку атрибутов блока
	 * @return
	 */	
	protected void setBlockFieldsFromBlock(Block block){

		tfTimeS.setText(block.getS());
		tfTimePo.setText(block.getPo());
		tfTitleBlock.setText(block.getBlockAtrTitle());
		//hfilenameLink.setText(selectedBlock.getFileName());
		hfilenameLink.setText(
				block.getFileName().substring( 					
						block.getFileName().lastIndexOf('\\') + 1,
						block.getFileName().length())
				);

		lDuration.setText(block.getDuration());
		fullFileName = block.getFileName();
		block_type = block.getBlockAtrType();
	}

	
	/**
	 * Формирует строку атрибутов блока
	 * @return
	 */	
	protected String getTagAttrsFromFields(){
				
		StringBuilder sb = new StringBuilder();
		sb.append("{");
		sb.append(block_type);
		
		sb.append(" С='");
		sb.append(getTimeFromField(tfTimeS.getText()));
		sb.append("'");
		sb.append(" По='");
		sb.append(getTimeFromField(tfTimePo.getText()));
		sb.append("'");
		sb.append(" Файл='");
		//sb.append(hfilenameLink.getText());
		sb.append(fullFileName);
		sb.append("'");
		sb.append(" Длительность='");
		sb.append(lDuration.getText());
		sb.append("'");
		sb.append(" Титр='");
		sb.append(tfTitleBlock.getText());
		sb.append("'}");
		return sb.toString();
	}

	private String getTimeFromField(String timeField){
		if (timeField.indexOf('_') >= 0){
			return "00:00:00";
		}
		return timeField;
	}

	public void newTag(String newTag) {
		tfTimeS.setText("00:00:00");
		tfTimePo.setText("00:00:00");
		hfilenameLink.setText("");
		fullFileName = "";
		block_type = newTag;
		lDuration.setText("");
		tfTitleBlock.setText("");
	}


	public void myShow() {
		setModal(true);
		center();
		setGlassEnabled(true);
		setText("Атрибуты тега1: " + block_type);
		show();
		tfTimeS.setFocus(true);
	}	
}
